'''
Created on Jun 6, 2012

@author: byron
'''
import wx
import ConfigParser
import os.path
import ast
import wx.lib.sized_controls as sc

CONFIG_FILE= "config.ini"

DEFAULT_SETTINGS = {
    "set_temp_day" : 25,
    "set_temp_night" : 25,
    "light_on" : 17,
    "light_off" : 5,
    "set_hum" : 50,
    "refresh_rate" : 3000,
    "simulate_device" : False,
    "fan_off_offset" : 0.2,
    "fan_on_offset" : 0.6,
    "fan_off_hum_offset" : 3,
    "fan_on_hum_offset" : 0,
    "heater_off_offset" : 0.2,
    "heater_on_offset" : 0.5,
    "serial_port" : "COM1"
}

class Settings:
    """
        @Settings
        This class is designed to handle the loading and 
        saving of local preferences/configurations for the
        application. It is also used to pass settings between 
        the main application frame and other windows 
        such as the settings frame.
    """
    
    def __init__(self):
        
        """ 
            Checks to see if a config file exists: 
            If not create one based off the default settings.
            If a config file already exists attempt to read the file
            and store the values on this instance
        """
        
        self.config = ConfigParser.ConfigParser()
                        
        if not os.path.isfile(CONFIG_FILE):
            self.CreateConfigFile()
        
        self.config.read(CONFIG_FILE)
        
        for key in DEFAULT_SETTINGS:
            try:
                value = ast.literal_eval(self.config.get("General", key))
            except Exception:
                value = DEFAULT_SETTINGS[key]
                
            self.__dict__[key] = value


    def CreateConfigFile(self):
               
        cfg = open(CONFIG_FILE, "w")
        self.config.add_section("General")

        for key, item in DEFAULT_SETTINGS.iteritems():
            if isinstance(item, basestring):
                item = "\"{0}\"".format(item)
            self.config.set("General", key, item)

        self.config.write(cfg)        
        cfg.close() 
    
    def Save(self):
        
        cfg = open(CONFIG_FILE, "w")
        
        for key in DEFAULT_SETTINGS:
            item = self.__dict__[key]
            if isinstance(item, basestring):
                item = "\"{0}\"".format(item)
            self.config.set("General", key, item)

        self.config.write(cfg)
        
        
class SettingsDialog(sc.SizedDialog):

    def __init__(self, *args, **kwargs):
        
        self.config = kwargs['settings']
        del kwargs['settings'] 

        sc.SizedDialog.__init__(self, None, -1, "Settings", style=wx.DEFAULT_DIALOG_STYLE)
        
        pane = self.GetContentsPane()
        pane.SetSizerType("form")
        
        # Day Temp
        wx.StaticText(pane, -1, "Day Temp")
        self.scDayTemp = wx.SpinCtrl(pane, -1)
        self.scDayTemp.SetRange(15, 35)
        self.scDayTemp.SetValue(self.config.set_temp_day)
        
        # Night Temp
        wx.StaticText(pane, -1, "Night Temp")
        self.scNightTemp = wx.SpinCtrl(pane, -1)
        self.scNightTemp.SetRange(15, 35)
        self.scNightTemp.SetValue(self.config.set_temp_night)
        
        # Humidity
        wx.StaticText(pane, -1, "Humidity")
        self.scHumidity = wx.SpinCtrl(pane, -1)
        self.scHumidity.SetRange(15, 75)
        self.scHumidity.SetValue(self.config.set_hum)
        
        # Light On
        wx.StaticText(pane, -1, "Light On")
        self.scTimeOn = wx.SpinCtrl(pane, -1)
        self.scTimeOn.SetRange(0, 23)
        self.scTimeOn.SetValue(self.config.light_on)
        
        # Light Off
        wx.StaticText(pane, -1, "Light Off")
        self.scTimeOff = wx.SpinCtrl(pane, -1)
        self.scTimeOff.SetRange(0, 23)
        self.scTimeOff.SetValue(self.config.light_off)
        
        # Serial Port
        wx.StaticText(pane, -1, "Serial Port")
        self.txtSerialPort = wx.TextCtrl(pane, -1, self.config.serial_port)
        
        # Buttons
        self.SetButtonSizer(self.CreateStdDialogButtonSizer(wx.OK | wx.CANCEL))
        self.Bind(wx.EVT_BUTTON, self.OnOK, id = wx.ID_OK)
        self.Bind(wx.EVT_BUTTON, self.OnCancel, id = wx.ID_CANCEL)
        
        self.Fit()         
        self.SetMinSize(self.GetSize())
        
    
    def OnOK(self, event):
        self.config.set_temp_day   = self.scDayTemp.GetValue()
        self.config.set_temp_night = self.scNightTemp.GetValue()
        self.config.set_hum       = self.scHumidity.GetValue()
        self.config.light_on    = self.scTimeOn.GetValue()
        self.config.light_off   = self.scTimeOff.GetValue()
        self.config.serial_port   = self.txtSerialPort.GetValue()
        
        self.config.Save()
        self.EndModal(wx.ID_OK)
    
    def OnCancel(self, event):
        self.EndModal(wx.ID_CANCEL)
    